#include "audiocapture.h"
#include<QDebug>
AudioCapture::AudioCapture(QObject *parent) : QObject(parent)
{
    //初始化
    pAudioInput = nullptr;
    pFile = nullptr;
}

//开始录音
// 在AudioCapture类中添加以下功能

// 添加音频输入设备检查
QStringList AudioCapture::getAvailableDevices() {
    QStringList devices;
    foreach (const QAudioDeviceInfo &deviceInfo, QAudioDeviceInfo::availableDevices(QAudio::AudioInput)) {
        devices << deviceInfo.deviceName();
    }
    return devices;
}

// 添加音频电平监控
void AudioCapture::onAudioStateChanged(QAudio::State state) {
    if(state == QAudio::StoppedState && pAudioInput) {
        qDebug() << "录音停止，最大音量:" << m_maxVolume;
    }
}

// 修改startCapture方法
void AudioCapture::startCapture(QString filename) {
    QAudioDeviceInfo audioDeviceInfo = QAudioDeviceInfo::defaultInputDevice();
    if(audioDeviceInfo.isNull()) {
        QMessageBox::information(NULL, tr("Record"), tr("当前没有可用的录音设备"));
        return;
    }

    QAudioFormat format;
    format.setSampleRate(16000);
    format.setChannelCount(1);
    format.setSampleSize(16);
    format.setCodec("audio/pcm");
    format.setByteOrder(QAudioFormat::LittleEndian);
    format.setSampleType(QAudioFormat::SignedInt);

    if(!audioDeviceInfo.isFormatSupported(format)) {
        format = audioDeviceInfo.nearestFormat(format);
        qDebug() << "不支持请求的格式，使用最近的格式:"
                 << "采样率:" << format.sampleRate()
                 << "位深:" << format.sampleSize();
    }

    pFile = new QFile(filename);
    if(!pFile->open(QIODevice::WriteOnly | QIODevice::Truncate)) {
        qDebug() << "无法打开文件进行写入:" << filename;
        delete pFile;
        pFile = nullptr;
        return;
    }

    pAudioInput = new QAudioInput(format, this);
    connect(pAudioInput, &QAudioInput::stateChanged, this, &AudioCapture::onAudioStateChanged);
    pAudioInput->start(pFile);
}
void AudioCapture::stopCapture()
{
    if(pAudioInput != NULL)
    {
        // 停止录音
        pAudioInput->stop();
    }

    if(pFile != NULL)
    {
        // 关闭文件
        pFile->close();
        delete pFile;
        pFile = nullptr;
    }
}

AudioCapture::~AudioCapture()
{
    //释放资源
    if(pAudioInput != nullptr)
    {
        delete pAudioInput;
        pAudioInput = nullptr;
    }

    if(pFile != nullptr)
    {
        delete pFile;
        pFile = nullptr;
    }
}
